package com.we.wfc.security.controller;

import com.we.wfc.common.pojo.ResultPoJo;
import com.we.wfc.common.utils.CommonUtil;
import io.jsonwebtoken.Claims;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.http.HttpHeaders;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.oauth2.provider.authentication.OAuth2AuthenticationDetails;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import springfox.documentation.annotations.ApiIgnore;

import javax.servlet.http.HttpServletRequest;

/**
 * 认证服务
 *
 * @author zhangby
 * @date 27/1/20 3:41 pm
 */
@RestController
@RequestMapping("/g/security/")
@Api(tags = "认证服务")
public class SecurityController {

    /**
     * 解析token
     *
     * @return
     */
    @GetMapping("/token/parse")
    @ApiOperation(value = "解析token", notes = "解析token", produces = "application/json")
    public ResultPoJo<Claims> parseToken(@ApiIgnore HttpServletRequest request) {
        // 获取token
        String token = CommonUtil.emptyStr(request.getHeader(HttpHeaders.AUTHORIZATION))
                .orElseGet(() ->
                        CommonUtil.emptyStr(
                                ((OAuth2AuthenticationDetails) SecurityContextHolder.getContext()
                                        .getAuthentication().getDetails())
                                        .getTokenValue()
                        ).orElse(null)
                );
        //解析token
        Claims claims = CommonUtil.parseJWT(token);
        return ResultPoJo.ok(claims);
    }
}
